package cn.ibdsr.human.service.impl;

import cn.ibdsr.human.constant.BizConstants;
import cn.ibdsr.human.constant.IsDeleted;
import cn.ibdsr.human.constant.PublishEnum;
import cn.ibdsr.human.db.mapper.CompanyRecommendImgMapper;
import cn.ibdsr.human.db.mapper.CompanyRecommendMapper;
import cn.ibdsr.human.db.model.CompanyRecommend;
import cn.ibdsr.human.db.model.CompanyRecommendImg;
import cn.ibdsr.human.db.model.Job;
import cn.ibdsr.human.exception.BizExceptionEnum;
import cn.ibdsr.human.exception.BusinessException;
import cn.ibdsr.human.service.CompanyRecommendService;
import cn.ibdsr.human.transfer.companyrecommend.CompanyRecommendDTO;
import cn.ibdsr.human.transfer.companyrecommend.CompanyRecommendImgDTO;
import cn.ibdsr.human.transfer.companyrecommend.CompanyRecommendListDTO;
import cn.ibdsr.human.transfer.companyrecommend.CompanyRecommendQueryDTO;
import cn.ibdsr.human.transfer.job.JobOperatorDTO;
import cn.ibdsr.human.util.MybatisPlusPage;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description:
 * @author: cdl
 * @email: iamcimon@qq.com
 * @date: 2021/8/12 10:51
 */
@Service
@Slf4j
public class CompanyRecommendServiceImpl implements CompanyRecommendService {
    @Resource
    private CompanyRecommendMapper companyRecommendMapper;
    @Resource
    private CompanyRecommendImgMapper companyRecommendImgMapper;

    @Override
    public CompanyRecommendDTO getCompanyInformation(Long id) {
        CompanyRecommend companyRecommend = companyRecommendMapper.selectById(id);
        if (companyRecommend == null) {
            throw new BusinessException(BizExceptionEnum.COMPANY_NOT_EXISTED);
        }
        QueryWrapper<CompanyRecommendImg> companyRecommendImgQueryWrapper = new QueryWrapper<>();
        companyRecommendImgQueryWrapper.eq("company_id", companyRecommend.getId());
        companyRecommendImgQueryWrapper.eq("is_deleted", IsDeleted.NORMAL.getCode());
        List<CompanyRecommendImg> companyRecommendImgs = companyRecommendImgMapper.selectList(companyRecommendImgQueryWrapper);
        List<CompanyRecommendImgDTO> images = new ArrayList<>();
        for (int i = 0; i < companyRecommendImgs.size(); i++) {
            CompanyRecommendImg companyRecommendImg = companyRecommendImgs.get(i);
            CompanyRecommendImgDTO companyRecommendImgDTO = JSONObject.parseObject(JSONObject.toJSONString(companyRecommendImg), CompanyRecommendImgDTO.class);
            images.add(companyRecommendImgDTO);
        }
        CompanyRecommendDTO companyRecommendDTO = new CompanyRecommendDTO();
        companyRecommendDTO=JSONObject.parseObject(JSONObject.toJSONString(companyRecommend),CompanyRecommendDTO.class);
        companyRecommendDTO.setIsPublishDes(PublishEnum.valueOf(companyRecommend.getPublish() ? 1 : 0).getMessage());
        companyRecommendDTO.setUpdateTimeDes(companyRecommend.getUpdateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        companyRecommendDTO.setUrls(images);
        return companyRecommendDTO;
    }

    @Transactional
    @Override
    public Long save(Long userId, CompanyRecommendDTO companyRecommendDTO) {
        if (companyRecommendDTO.getId() == null) {
            return create(userId, companyRecommendDTO);
        } else {
            return modify(userId, companyRecommendDTO);
        }
    }

    @Override
    public CompanyRecommendListDTO getCompanies(CompanyRecommendQueryDTO companyRecommendQueryDTO) {
        if (companyRecommendQueryDTO.getPageNo() == null || companyRecommendQueryDTO.getPageNo() <= 0) {
            companyRecommendQueryDTO.setPageNo(1L);
        }
        if (companyRecommendQueryDTO.getPageSize() == null || companyRecommendQueryDTO.getPageSize() <= 0) {
            companyRecommendQueryDTO.setPageSize(BizConstants.DEFAULT_PAGE_SIZE);
        } else if (companyRecommendQueryDTO.getPageSize() > BizConstants.MAX_PAGE_SIZE) {
            throw new BusinessException(BizExceptionEnum.REQUEST_ERROR);
        }

        Page<CompanyRecommendDTO> page = MybatisPlusPage.defaultNewPage(companyRecommendQueryDTO);
        List<CompanyRecommendDTO> companiesList = companyRecommendMapper.getCompaniesList(page,
                companyRecommendQueryDTO.getName(), companyRecommendQueryDTO.getIsPublish()
        );
        List<Long> ids = new ArrayList<>();
        ConcurrentHashMap<Long, List<CompanyRecommendImgDTO>> imagesMap = new ConcurrentHashMap<>();
        if (companiesList.size() > 0) {
            for (CompanyRecommendDTO companyRecommendDTO : companiesList) {
                ids.add(companyRecommendDTO.getId());
            }
            QueryWrapper<CompanyRecommendImg> companyRecommendImgQueryWrapper = new QueryWrapper<>();
            companyRecommendImgQueryWrapper.in("company_id", ids);
            companyRecommendImgQueryWrapper.eq("is_deleted", IsDeleted.NORMAL.getCode());
            List<CompanyRecommendImg> companyRecommendImgs = companyRecommendImgMapper.selectList(companyRecommendImgQueryWrapper);
            for (int i = 0; i < companyRecommendImgs.size(); i++) {
                CompanyRecommendImg companyRecommendImg = companyRecommendImgs.get(i);
                CompanyRecommendImgDTO companyRecommendImgDTO = JSONObject.parseObject(JSONObject.toJSONString(companyRecommendImg), CompanyRecommendImgDTO.class);
                if (imagesMap.containsKey(companyRecommendImg.getCompanyId())) {
                    List<CompanyRecommendImgDTO> strings = imagesMap.get(companyRecommendImg.getCompanyId());
                    strings.add(companyRecommendImgDTO);
                } else {
                    List<CompanyRecommendImgDTO> strings = new ArrayList<>();
                    strings.add(companyRecommendImgDTO);
                    imagesMap.put(companyRecommendImg.getCompanyId(), strings);
                }

            }

        }
        Long pageIdex = page.getSize() * (page.getCurrent() - 1);
        // 创建返回结果
        for (CompanyRecommendDTO companyRecommendDTO : companiesList) {
            pageIdex++;
            companyRecommendDTO.setIsPublishDes(PublishEnum.valueOf(companyRecommendDTO.getIsPublish() ? 1 : 0).getMessage());
            companyRecommendDTO.setUpdateTimeDes(companyRecommendDTO.getUpdateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            companyRecommendDTO.setUrls(imagesMap.get(companyRecommendDTO.getId()));
            companyRecommendDTO.setRank(pageIdex);
        }
        page.setRecords(companiesList);
        CompanyRecommendListDTO companyRecommendListDTO = new CompanyRecommendListDTO();
        companyRecommendListDTO.setPageNo(page.getCurrent());
        companyRecommendListDTO.setPageSize(page.getSize());
        companyRecommendListDTO.setTotalPage(page.getPages());
        companyRecommendListDTO.setTotalCount(page.getTotal());
        companyRecommendListDTO.setData(page.getRecords());
        return companyRecommendListDTO;
    }

    /**
     * @param userId
     * @param operatorDTO
     * @return
     */
    @Override
    public Long publishOrNot(Long userId, JobOperatorDTO operatorDTO) {
        CompanyRecommend companyRecommend = companyRecommendMapper.selectById(operatorDTO.getId());
        if (companyRecommend == null || companyRecommend.getDeleted().equals(IsDeleted.DELETED.getCode() > 0)) {
            throw new BusinessException(BizExceptionEnum.COMPANY_NOT_EXIST);
        }
        if (companyRecommend.getPublish().equals(operatorDTO.getIsPublish())) {
            return companyRecommend.getId();
        }
        CompanyRecommend tempCompanyRecommend = new CompanyRecommend();
        tempCompanyRecommend.setId(companyRecommend.getId());
        tempCompanyRecommend.setUpdateUser(userId);
        tempCompanyRecommend.setUpdateTime(LocalDateTime.now());
        tempCompanyRecommend.setPublish(operatorDTO.getIsPublish());
        companyRecommendMapper.updateById(tempCompanyRecommend);
        return tempCompanyRecommend.getId();
    }

    @Transactional
    @Override
    public Long delete(Long userId, Long id) {
        CompanyRecommend companyRecommend = companyRecommendMapper.selectById(id);
        if (companyRecommend == null || companyRecommend.getDeleted().equals(IsDeleted.DELETED.getCode() > 0)) {
            throw new BusinessException(BizExceptionEnum.COMPANY_NOT_EXIST);
        }

        if (companyRecommend.getPublish().equals(PublishEnum.YES.getCode()>0)) {
            throw new BusinessException(BizExceptionEnum.CANCEL_COMPANY);
        }
        companyRecommendImgMapper.deleteImages(companyRecommend.getId());
        companyRecommend.setUpdateUser(userId);
        companyRecommend.setUpdateTime(LocalDateTime.now());
        companyRecommend.setDeleted(IsDeleted.DELETED.getCode() > 0);
        companyRecommendMapper.updateById(companyRecommend);
        return companyRecommend.getId();
    }

    /**
     * 获取推荐企业列表
     *
     * @return
     */
    @Override
    public List<CompanyRecommendDTO> getLatestCompanies() {
        List<CompanyRecommendDTO> list = companyRecommendMapper.getLatestCompanies();
        return list;
    }

    /**
     * 修改企业信息
     *
     * @param userId
     * @param companyRecommendDTO
     * @return
     */
    private Long modify(Long userId, CompanyRecommendDTO companyRecommendDTO) {
        CompanyRecommend companyRecommend = companyRecommendMapper.selectById(companyRecommendDTO.getId());
        if (companyRecommend == null) {
            throw new BusinessException(BizExceptionEnum.COMPANY_NOT_EXIST);
        }
        if (companyRecommendDTO.getDetail().length() > BizConstants.DETAIL_SIZE) {
            throw new BusinessException(BizExceptionEnum.COMPANY_DETIAL_LENGTH_LIMIT);
        }
        companyRecommendImgMapper.batchDelete(companyRecommend.getId());
        CompanyRecommend companyRecommendNew = new CompanyRecommend();
        companyRecommendNew.setName(companyRecommendDTO.getName());
        companyRecommendNew.setDetail(companyRecommendDTO.getDetail());
        companyRecommendNew.setUpdateUser(userId);
        companyRecommendNew.setId(companyRecommendDTO.getId());
        companyRecommendNew.setPublish(companyRecommendDTO.getIsPublish());
        companyRecommendNew.updateById();
        if (companyRecommendDTO.getUrls() != null) {
            for (int i = 0; i < companyRecommendDTO.getUrls().size(); i++) {
                CompanyRecommendImgDTO companyRecommendImgDTO = companyRecommendDTO.getUrls().get(i);
                CompanyRecommendImg companyRecommendImg = new CompanyRecommendImg();
                companyRecommendImg.setCompanyId(companyRecommendDTO.getId());
                companyRecommendImg.setUrl(companyRecommendImgDTO.getUrl());
                companyRecommendImgMapper.insert(companyRecommendImg);
            }
        }
        return companyRecommend.getId();
    }

    /**
     * 增加企业信息
     *
     * @param userId
     * @param companyRecommendDTO
     * @return
     */
    private Long create(Long userId, CompanyRecommendDTO companyRecommendDTO) {
        if (companyRecommendDTO.getDetail().length() > BizConstants.DETAIL_SIZE) {
            throw new BusinessException(BizExceptionEnum.COMPANY_DETIAL_LENGTH_LIMIT);
        }
        CompanyRecommend companyRecommendNew = new CompanyRecommend();
        companyRecommendNew.setName(companyRecommendDTO.getName());
        companyRecommendNew.setDetail(companyRecommendDTO.getDetail());
        companyRecommendNew.setCreateUser(userId);
        companyRecommendNew.setPublish(companyRecommendDTO.getIsPublish());
        companyRecommendMapper.insert(companyRecommendNew);
        if (companyRecommendDTO.getUrls() != null) {
            for (int i = 0; i < companyRecommendDTO.getUrls().size(); i++) {
                CompanyRecommendImgDTO companyRecommendImgDTO = companyRecommendDTO.getUrls().get(i);
                CompanyRecommendImg companyRecommendImg = new CompanyRecommendImg();
                companyRecommendImg.setCompanyId(companyRecommendNew.getId());
                companyRecommendImg.setUrl(companyRecommendImgDTO.getUrl());
                companyRecommendImgMapper.insert(companyRecommendImg);
            }
        }
        return companyRecommendNew.getId();
    }
}
